import api from './apiList';
import axios from 'axios';
import querystring from 'querystring';
import {server_config} from '../config/config.js';



var serverPort = server_config.URL + ":" + server_config.PORT;
const instance = axios.create({
  baseURL: serverPort,
  timeout: 20000,
  validateStatus:function(status){
    return status < 500;
  },
  headers: {
    // 跨域请求 这个配置不能少
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    'Accept': 'application/json'
  }
});

//通过axios发送请求
export default {
  /**
   * @param urlKey 对应API 中的urlkey
   * @param paramObj  发送ajax 传递的参数对象
   * @returns {promise} 返回promise对象
   * @example
   axios.get('/user', {
      params: {
        ID: 12345
      }
    })
     .then(function (response) {
      console.log(response);
    })
     .catch(function (response) {
      console.log(response);
    });
   */
  get:function(urlKey, paramObj){
    var apiStr = serverPort + api[urlKey];
    return axios.get(apiStr,paramObj);
  },

  /**
   * @param urlKey 对应API 中的urlkey
   * @param paramObj  发送ajax 传递的参数对象
   * @returns {promise} 返回promise对象
   * @example
   axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
   .then(function (response) {
    console.log(response);
  })
   .catch(function (response) {
    console.log(response);
  });
   */
  post:function(urlKey,paramObj){
    var apiStr = serverPort + api[urlKey];
    return instance.post(apiStr,querystring.stringify(paramObj));
  },

  /**
   * @param configObj 发送ajax 的配置参数
   * @returns {promise} 返回promise对象
   * @example
   axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
   */
  axios:function(configObj){
    return axios(configObj);
  },

  all:function(){
    axios.all(arguments).then(axios.spread(function () {
      console.dir(arguments);
    }));
  }
}
